package com.crazy.security;

import static com.crazy.security.ValidateCodeBean.VALIDCODE;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;

/**
 * 带验证码的用户名密码验证过滤器
 * 
 * @author zhang weiwei
 * @since 2013-9-16下午3:10:40
 */
public class MyUsernamePasswordAuthenticationFilter extends
		UsernamePasswordAuthenticationFilter {
	public static final String VALIDCODE_KEY = "j_validCode";
	public static final String VALIDCODE_ERRORKEY = "validCode.notEquals";
	private String validCodeParameter = VALIDCODE_KEY;
	private String validCodeErrorKey = VALIDCODE_ERRORKEY;
	private boolean enabledValidCode = true;

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request,
			HttpServletResponse response) throws AuthenticationException {
		if (this.enabledValidCode) {
			HttpSession session = request.getSession();
			// 保存在session中的图片验证码
			String validCode = (String) session.getAttribute(VALIDCODE);
			// 用户输入的验证码
			String j_validCode = request.getParameter(this.validCodeParameter);
			if (!StringUtils.hasText(j_validCode)
					|| !validCode.equalsIgnoreCase(j_validCode)) {
				String msg = this.messages.getMessage(this.validCodeErrorKey);
				throw new AuthenticationServiceException(msg);
			}
		}
		return super.attemptAuthentication(request, response);
	}

	public String getValidCodeParameter() {
		return validCodeParameter;
	}

	public void setValidCodeParameter(String validCodeParameter) {
		this.validCodeParameter = validCodeParameter;
	}

	public String getValidCodeErrorKey() {
		return validCodeErrorKey;
	}

	public void setValidCodeErrorKey(String validCodeErrorKey) {
		this.validCodeErrorKey = validCodeErrorKey;
	}

	public boolean isEnabledValidCode() {
		return enabledValidCode;
	}

	public void setEnabledValidCode(boolean enabledValidCode) {
		this.enabledValidCode = enabledValidCode;
	}
}
